package com.wym.rbac.service.impl;
import com.wym.rbac.common.Constants;
import com.wym.rbac.domain.Employee;
import com.wym.rbac.domain.vo.LoginInfoVo;
import com.wym.rbac.mapper.EmployeeMapper;
import com.wym.rbac.mapper.PermissionMapper;
import com.wym.rbac.service.ILoginService;
import com.wym.rbac.utils.RedisUtils;
import com.wym.rbac.utils.VerifyCodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements ILoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Employee login(LoginInfoVo loginInfoVo, HttpServletRequest request) throws Exception {
        // 1 非法参数
        Assert.notNull(loginInfoVo, "非法参数");

        // 2 校验验证码
        String verifyCode = redisUtils.get(Constants.VERIFY_CODE + ":" + loginInfoVo.getUuid());
        Assert.notNull(verifyCode, "验证码不存在");

        Assert.state(VerifyCodeUtil.verification(loginInfoVo.getCode(), verifyCode, true),
                "验证码输入错误");

        // 3 登录
        Employee loginEmployee = employeeMapper.login(loginInfoVo);
        Assert.notNull(loginEmployee, "姓名或密码输入错误");

        // 4 登录成功后，存储登录用户，存储相应的权限
        ObjectMapper mapper = new ObjectMapper();
        String loginEmployeeJson = mapper.writeValueAsString(loginEmployee);
        redisUtils.set(Constants.LOGIN_EMPLOYEE + ":" + loginEmployee.getId(), loginEmployeeJson);

        // 查询登录员工的权限
        List<String> expression = permissionMapper.selectExpressionByEmpId(loginEmployee.getId());
        String expressionJson = mapper.writeValueAsString(expression);
        redisUtils.set(Constants.EXPRESSION + ":" + loginEmployee.getId(), expressionJson);

        return loginEmployee;
    }

    @Override
    public Map<String, String> verifyCode() {
        Map<String, String> map = VerifyCodeUtil.generateVerifyCode();
        String uuid = map.get("uuid");
        String code = map.get("code");

        // 存储到 Redis 中
        redisUtils.set(Constants.VERIFY_CODE + ":" + uuid, code, Constants.CODE_EXPIRES);

        // 不需要返回具体验证码
        map.remove("code");
        return map;
    }

    @Override
    public void logout(String userId) {
        // 清除 Redis 登录数据
        String loginEmployeeJson = redisUtils.get(Constants.LOGIN_EMPLOYEE + ":" + userId);
        Assert.notNull(loginEmployeeJson, "非法参数");
        redisUtils.del(Constants.LOGIN_EMPLOYEE + ":" + userId);
        redisUtils.del(Constants.EXPRESSION + ":" + userId);
    }
}